'use strict';

import { merchantModel } from "../model/merchant";
import { ServiceBase, Exceptions } from '../kalend';
import { merchant_commentService } from "./merchant_comment";
import { merchant_disheService } from "./merchant_dishe";
import { common } from "../middleware/common";
import { wechatService } from "./wechat";
import { ObjectId } from "bson";
import { merchant_wineService } from "./merchant_wine";
import { platform_userService } from "./platform_user";
import { customer_accountService } from "./customer_account";
import { merchantapplywineService } from "./MerchantApplyWine";
import { platformjoinnews_Service } from "./platform_joinnews";
import { customer_orderwineService } from "./customer_orderwine";
var moment = require('moment');

class MerchantService extends ServiceBase {
    constructor() {
        super(merchantModel)
    }
    async query(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const status = params.status;
        const state = params.state;
        const bondstatus = params.bondstatus;
        const name = params.name;
        // const regstarttime = params.regstarttime;
        // const regendtime = params.regendtime;
        const upstarttime = params.upstarttime;
        const upendtime = params.upendtime;
        const agent = params.agent;
        const filter: any = {};
        if (name) {
            filter.$or = [{ name: { '$regex': name, $options: 'i' } }, { address: { '$regex': name, $options: 'i' } }, { legalpersonname: { '$regex': name, $options: 'i' } }];
        }
        // if (regstarttime) {
        //     filter.createTime = { '$gte': new Date(regstarttime) };
        // }
        // if (regendtime) {
        //     if (filter.createTime) {
        //         filter.createTime['$lte'] = new Date(regendtime);
        //     } else {
        //         filter.createTime = { '$lte': new Date(regendtime) };
        //     }
        // }
        if (upstarttime) {
            filter.applytime = { '$gte': new Date(moment(new Date(upstarttime)).format('YYYY-MM-DD') + '  00:00:00') };
        }
        if (upendtime) {
            if (filter.applytime) {
                filter.applytime['$lte'] = new Date(moment(upendtime).format('YYYY-MM-DD') + '  23:59:59');
            } else {
                filter.applytime = { '$lte': new Date(moment(upendtime).format('YYYY-MM-DD') + '  23:59:59') };
            }
        }
        if (status && status !== 'all') {
            filter.status = status;
        }
        if (state && state != 'all') {
            filter.state = state;
        }
        if (bondstatus && bondstatus != 'all') {
            filter.bondstatus = bondstatus;
        }
        if (agent && agent != '') {
            filter.agent = new ObjectId(agent);
        }
        let result = await super.queryPagination(offset, limit, {
            filter: filter,
            select: 'balance coinbalance mealbalance agentrate legalpersonname legalpersontel name legaluserid address bondstatus state createTime applytime status agent createuser modifyuser modifytime BankCardNumber Bank rate logoimage star',
            populateOptions: [
                {
                    path: 'legaluserid',
                    select: 'name customerid balance'
                },
                {
                    path: 'agent',
                    select: 'name'
                },
                {
                    path: 'createuser',
                    select: 'name'
                },
                {
                    path: 'modifyuser',
                    select: 'name'
                }
            ]
        });
        for (let index = 0; index < result.rows.length; index++) {
            let item = result.rows[index];
            // if (item.legalpersontel) {
            //     item.legalpersontel = item.legalpersontel.substring(0, 3) + '****' + item.legalpersontel.substring(7, item.legalpersontel.length);
            // }
            if (item.legaluserid) {
                item.legaluser = item.legaluserid.name;
                item.legalusercusid = item.legaluserid.customerid;
                item.balanceviter = item.legaluserid.balance || 0;
                delete item.legaluserid;
            }
            if (item.agent) {
                item.agent = item.agent.name;
                delete item.agent;
            }
            if (item.createuser) {
                item.createuser = item.createuser.name;
                delete item.createuser;
            }
            if (item.modifyuser) {
                item.modifyuser = item.modifyuser.name;
                delete item.modifyuser;
            }
            if (item.status == '0') {
                item.status = '禁用';
            } else if (item.status == '1') {
                item.status = '有效';
            }
            // 状态 0:未申请 1：待审核 2：已通过 9：已退回
            switch (Number(item.state)) {
                case 0:
                    item.state = '未申请';
                    break;
                case 1:
                    item.state = '待审核';
                    break;
                case 2:
                    item.state = '已通过';
                    break;
                case 9:
                    item.state = '已退回';
                    break;
                default:
                    break;
            }
            // 押金状态 0:未缴纳 1：已缴纳 9：已退款
            switch (item.bondstatus) {
                case 0:
                    item.bondstatus = '未缴纳';
                    break;
                case 1:
                    item.bondstatus = '已缴纳';
                    break;
                case 9:
                    item.bondstatus = '已退款';
                    break;
                default:
                    break;
            }
            item.inviterNum = 0;
            // 查询商户邀请会员数量
            let cus = await platform_userService.querySingle({ merchantid: item._id, status: 1 }, { select: 'customerid' });
            if (cus) {
                const num = await customer_accountService.count({ inviter: cus._icustomeridd, status: 1, ismember: true });
                item.inviterNum = num;
            }
        }
        return result;
    }
    async queryByPoint(pars: any) {
        const lng: number = pars.lng;
        const lat: number = pars.lat;
        //const lng: number = 121.48941;
        //const lat: number = 31.40527;
        const title = pars.title;
        const cuisine = pars.cuisine;
        //默认500公里以内
        const distance: number = pars.distance || 500;
        const type: number = pars.type;
        const percapita = pars.percapita;
        const offset: number = pars.offset;
        const limit: number = pars.limit;

        let filter: any = {
            status: 1
            //location: { $near: [lng, lat] }
        };
        if (title) {
            filter.name = { $regex: title, $options: 'i' };
        }
        if (cuisine) {
            filter.cuisine = { $in: [cuisine] };
        }
        // 智能排序 todo
        if (type) {

        }
        if (percapita) {
            if (percapita.indexOf('<') >= 0) {
                filter.percapita = { $lte: parseFloat(percapita.replace('<', '')) };
            }
            else if (percapita.indexOf('>') >= 0) {
                filter.percapita = { $gte: parseFloat(percapita.replace('>', '')) };
            } else {
                const ps = percapita.split('-');
                if (ps.length == 2) {
                    filter.percapita = { $gte: parseFloat(ps[0]), $lte: parseFloat(ps[1]) };
                }
            }
        }
        let dbsql = this.Model.aggregate([
            {
                $geoNear: {
                    near: { type: "Point", coordinates: [lng, lat] },
                    key: "loc",
                    maxDistance: distance * 1000,
                    distanceField: "distance",
                    query: filter,
                    spherical: true
                }
            },
            // {
            //     $match: filter
            // },
            {
                $project: {
                    _id: "$_id",
                    name: "$name",
                    distance: "$distance",
                    cuisine: "$cuisine",
                    location: "$location",
                    ad_info: "$ad_info",
                    logoimage: "$logoimage",
                    percapita: "$percapita",
                    star: "$star"
                }
            }
            // ,
            // {
            //     $skip: (offset - 1) * limit
            // },
            // {
            //     $limit: limit
            // }
        ]);
        let total = await dbsql;
        let data = await dbsql.skip((offset - 1) * limit).limit(limit);
        data = data.map((item) => {
            item.distance = (item.distance / 1000).toFixed(3);
            return item;
        });
        return {
            offset: offset,
            limit: limit,
            rows: data,
            total: total,
            totalpage: Math.ceil(total.length / limit)
        }

        // let data = await this.queryPagination(offset || 1, limit || 10, {
        //     filter: filter,
        //     select: 'name cuisine location logoimage percapita star'
        // });
        // //var apiurl = config.get("apiforarea")["imgurl"]
        // let result = data.rows.map((item) => {
        //     if (item.location) {
        //         let p1 = turf.point([parseFloat(item.location.lng), parseFloat(item.location.lat)]);
        //         let p2 = turf.point([lng, lat]);
        //         let distance = turf.distance(p1, p2, { units: 'kilometers' }).toFixed(3);
        //         item.distance = Number(distance);
        //     }
        //     // if (item.headmig) {
        //     //     item.headmig = apiurl + item.headmig;
        //     // }
        //     return item;
        // });
        // if (distance) {
        //     result = result.filter((row) => {
        //         return row.distance <= distance;
        //     });
        // }
        // result = result.sort((a, b) => {
        //     return a.distance > b.distance ? 1 : 0;
        // })
        // return result;
    }
    async queryBId(mid: any) {
        // 商户信息
        let data = await this.querySingle({ _id: mid, status: 1 }, { select: 'name tel cuisine location ad_info address logoimage percapita star info' });
        if (data) {
            if (data.cuisine) {
                data.cuisine = data.cuisine.join(',');
            }
            // 评价信息
            data.comments = await merchant_commentService.query({ offset: 1, limit: Number.MAX_SAFE_INTEGER, mid: mid });
            // 菜品
            data.dishes = await merchant_disheService.querypage({ offset: 1, limit: Number.MAX_SAFE_INTEGER, mid: mid });
            // 酒水、饮料
            data.wines = await merchant_wineService.querypage({ offset: 1, limit: Number.MAX_SAFE_INTEGER, mid: mid });

        }
        return data;
    }
    async queryByUserId(doc: any) {
        // 商户信息
        let filter = {
            legaluserid: doc.userid
        }
        let data = await this.queryPagination(doc.offset, doc.limit, {
            filter: filter,
            populateOptions: {
                path: 'legaluserid',
                select: 'name balance'
            }
        });

        data.rows = data.rows.map((item) => {
            item.rate = item.rate + '%';
            item.balanceviter = item.legaluserid ? item.legaluserid.balance || 0 : 0;
            return item;

        });
        // if (data.lable)
        //     data.lable = data.lable.split(',').split('，').split(';').split('；').split(' ').split('、').split('.');
        // // 评价信息
        // data.comments = await merchant_commentService.query({ offset: 1, limit: 15, mid: mid });
        // // 菜品
        // data.dishes = await merchant_disheService.queryall(mid);
        return data;
    }

    async lock(userid: any) {
        return this.update(userid, { status: 0 });
    }
    async open(userid: any) {
        return this.update(userid, { status: 1 });
    }
    async save(doc: any) {
        if (doc._id) {
            let data = await this.queryById(doc._id);
            // 根据位置获取经纬度
            if (doc.address != data.address) {
                let addinfo = await wechatService.getlocation(doc.address);
                doc.location = addinfo.location;
                doc.ad_info = addinfo.address_components;
                doc.ad_info.adcode = addinfo.ad_info.adcode;
                doc.loc = [addinfo.location.lng, addinfo.location.lat];
            }
            // 同步餐厅法人关联餐厅
            if (doc.legaluserid) {
                const pyuser = await platform_userService.update(doc.legaluserid, { merchantid: doc._id });
                customer_accountService.update(pyuser.customerid, { legaluserid: doc.legaluserid, agent: doc.agent });
            }
            return this.update(doc._id, doc);
        } else {
            // 根据位置获取经纬度
            if (doc.address) {
                let addinfo = await wechatService.getlocation(doc.address);
                doc.location = addinfo.location;
                doc.ad_info = addinfo.address_components;
                doc.ad_info.adcode = addinfo.ad_info.adcode;
                doc.loc = [addinfo.location.lng, addinfo.location.lat];
            }
            doc.code = common.buildCode();
            const mer = await this.create(doc);
            // 同步餐厅法人关联餐厅
            if (doc.legaluserid) {
                const pyuser = await platform_userService.update(doc.legaluserid, { merchantid: mer._id });
                customer_accountService.update(pyuser.customerid, { legaluserid: doc.legaluserid, agent: doc.agent });
            }
            // 创建餐厅酒水
            merchant_wineService.initWine(mer._id);
            // 创建餐厅快讯
            let newdoc: any = {
                merchantid: mer._id,
                newstitle: '热烈欢迎' + mer.name,
                newsthumbnail: mer.logoimage,
                newspic: mer.logoimage,
                merchantName: mer.name,
                merchantlabel: mer.cuisine
            };
            platformjoinnews_Service.create(newdoc);
            return mer;
        }
    }
    async queryall() {
        return this.queryAll({
            filter: { status: 1 },
            select: 'name'
        });
    }

    async queryAlls(filter: any) {
        return super.queryAll({ filter: filter });
    }

    async queryone(doc: any) {
        let data = await this.querySingle({ _id: doc._id }, {
            populateOptions: {
                path: 'legaluserid',
                select: 'name balance'
            }
        });
        data.balanceviter = data.legaluserid ? data.legaluserid.balance || 0 : 0;
        data.type = '餐费账户';
        return data;
    }

    async queryBymid(mid: any) {
        return await this.queryById(mid);
    }

    //查询合伙人名下的餐厅
    async querybyagent(parms: any) {
        const offset: number = parms.offset;
        const limit: number = parms.limit;
        const agent = parms.userid;
        const mname = parms.mname;
        const filter: any = {};
        filter.agent = agent;
        if (mname) {
            filter.name = mname;
        }

        let data = await this.queryPagination(offset, limit, {
            filter: filter
        });
        for (let index = 0; index < data.rows.length; index++) {
            const item = data.rows[index];
            item.inviterNum = 0;
            // 查询商户邀请会员数量
            let cus = await platform_userService.querySingle({ merchantid: item._id, status: 1 }, { select: 'customerid' });
            if (cus) {
                const num = await customer_accountService.count({ inviter: cus.customerid, status: 1, ismember: true });
                item.inviterNum = num;
            }
        }
        return data;
    }

    async queryweinmax(mid: any) {
        //查询商户酒水消费数量
        let costcount: any = await customer_orderwineService.queryWineCost(mid);

        //商户已补货
        let appCount: any = await merchantapplywineService.queryWineApply(mid);

        let maxnum = costcount - appCount;
        // 获取餐厅酒水信息
        let wines = await merchant_wineService.querybymerchantidcan(mid);
        return {
            winelist: wines.items,
            maxnum: maxnum,
            appcount: wines.appcount
        };
    }

    async addwine(wid: any){
        let data= await this.queryAll({filter:{status: 1},select:'name'});
        let items:Array<any>=[];
        data.map((a)=>{
            let obj:any={};
            obj.stock =0;
            obj.status =0;
            obj.count =0;
            obj.wineid = wid;
            obj.merchantid = a._id;
            items.push(obj);
        });
        merchant_wineService.createMany(items);
    }
}

export const merchantService = new MerchantService();